﻿using System.Data;
using System.Data.SqlClient;
using NUnit.Framework;
using System;

namespace SDG.UnitTesting.Example
{
    [TestFixture]
    public class TestMethods_Setup
    {
        [TestFixtureSetUp]
        public void Setup()
        {
            SDGConsoleWrapper cons = new SDGConsoleWrapper(@"Database\SampleDatabase.sqlgen");
            cons.Execute();
        }

        [Test]
        public void Test_TablesPopulated()
        {
            SqlConnection sqlConn = new SqlConnection("Server=.;Database=SampleDatabase;;Integrated Security=True");
            SqlCommand sqlCmd = new SqlCommand("SELECT Count(*) FROM TestTable", sqlConn);
            SqlCommand sqlCmd2 = new SqlCommand("SELECT Count(*) FROM TestTable2", sqlConn);

            try
            {
                sqlConn.Open();

                int T1 = (int)sqlCmd.ExecuteScalar();
                int T2 = (int)sqlCmd2.ExecuteScalar();

                Assert.AreEqual(1000, T1);
                Assert.AreEqual(1000, T2);
            }
            finally
            {
                if(sqlConn.State == ConnectionState.Open)
                    sqlConn.Close();
            }
        }

        // won't win any cryptographic prizes, but its
        // just to deter someone from trying to find other IDs
        // and messing things up.
        // could be cracked with basic cryptanalysis
        private const int F = 0x37b0364c;

        /// <summary>
        /// Encodes the number as an unsigned int
        /// </summary>
        /// <param name="number">The number to encode</param>
        /// <returns>The encoded number</returns>
        public static int Encode(int number)
        {
            int xord = number ^ F;
            return (int)(((xord & 0xffff0000) >> 16) | ((xord & 0xffff) << 16));
        }

        /// <summary>
        /// Decodes the number as a signed int
        /// </summary>
        /// <param name="number">The number to decode</param>
        /// <returns>The decoded number</returns>
        public static int Decode(int number)
        {
            int unxord = (int)(((number & 0xffff0000) >> 16) | ((number & 0xffff) << 16));
            return unxord ^ F;
        }


        [Test]
        public void x()
        {
            int x = Encode(Int32.MaxValue);
            Console.WriteLine("Encoded " + x);
            Console.WriteLine(Convert.ToInt32(x));
            int x2 = Decode(x);
            Console.WriteLine("Decoded " + x2);
        }
    }
}